﻿@COFE ?= {}
Link = COFE.Link
utils = COFE.utils


# MODEL - Represents a COFEWS Entry.
class Entry extends Spine.Model
  # id - identify the Entry in COFEFS.
  # label - display text.
  # path - full parse path.
  # basetype - "folder" or "file"
  # time - last write time in Date format, use @timeStr for string.
  # icon - icon image url.
  # length - file size.
  # subfoldercount - folder's sub-folder count. (optional)
  # filecount - folder's sub-file count. (optional)
  @configure 'Entry', 'id', 'label', 'path', 'basetype', 'time', 'links', 'icon', 'length', 'subfoldercount', 'filecount'

  init : =>
    @timeStr = @time?.toString('d-MM-yy')
  
  # Uses to compare two entries, uses in sort or equals.
  compare : (anotherItem) ->    
    (if @basetype != anotherItem.basetype 
    then (if @basetype is "folder" then -1 else 1) 
    else (if @path < anotherItem.path then -1 else 1))

  # Construct entry from cache using it's id, or return null if it's not cached.
  Entry.fromId = (id) ->
    Entry.findByAttribute('id', id) 

  # Construct entry from COFEWS Entry json element.
  Entry.fromJson = (data) ->
    entry = Entry.fromId(data.id)
    if entry isnt null 
      return entry

    entry = Entry.init({ 
      id : data.id
      label : utils.extractFilename(data.path)
      path : data.path
      basetype : data.basetype.toLowerCase()
      time : Date.parse(data.time)      
      links : {}
    })
    
    for link in data.links
      linkObj = Link.fromJson(link)
      entry.links[linkObj.rel] = linkObj
      if linkObj.rel is "typeInfo" and entry.icon is undefined
        entry.icon = linkObj.url + "?" + COFE.iconUrlAtb
      else if linkObj.rel is "thumbnail" or linkObj.rel is "icon"
        entry.icon = linkObj.url + "?" + COFE.defUrlAtb

    if entry.basetype is "file"
      entry.length = data.size

    if entry.basetype is "folder"
      entry.subfoldercount = data.subfoldercount 
      entry.filecount = data.filecount
      entry.hassubfolders = @subfoldercount? > 0
      entry.hasfiles = @filecount? > 0
      entry.totalcount = entry.subfoldercount + entry.filecount

    entry.save()        
    entry    



COFE.Entry = Entry
